﻿using Microsoft.Extensions.Caching.Memory;
using Polly;
using Polly.Caching;
using Polly.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common
{
    public class Cache : DemoBase
    {
        public override string DemoName => "Polly-Cache Demo";

        public override async void RunDemo()
        {
            base.Init();

            var memoryCache = new MemoryCache(new MemoryCacheOptions());
            IAsyncCacheProvider memoryCacheProvider = new MemoryCacheProvider(memoryCache);

            AsyncCachePolicy cache = Policy.CacheAsync(memoryCacheProvider, ttl: TimeSpan.FromMinutes(30));//此处可以传递更多细节配置 当前仅设置了缓存超时时长

            for (int i = 0; i < 5; i++)
            {
                string orderId = "12345678";
                Context policyExecutionContext = new Context("GetOrder-By-Id-");
                policyExecutionContext["orderId"] = orderId;
                var result = await cache.ExecuteAsync(async context =>await GetOrderInfoById(orderId), policyExecutionContext);
                PrintInfo($"订单详情：{result}");
                Thread.Sleep(i * 1000);

                var x = memoryCache.Get(policyExecutionContext.OperationKey);
                memoryCache.Remove(policyExecutionContext.OperationKey);
                await memoryCacheProvider.PutAsync(policyExecutionContext.OperationKey, string.Empty, new Ttl(TimeSpan.FromSeconds(30)), CancellationToken.None, false);
            }
        }

        private Task<string> GetOrderInfoById(string orderId)
        {
            PrintInfo("从数据获取订单信息");
            var result = $"订单号：{orderId} 订单金额：￥{124.5}";
            return Task.FromResult(result);
        }
    }
}
